import React, {useEffect, useState,useRef} from 'react';
import {
    Card,
    Form,
    List,
    Select,
    Tag,
    Input,
    Space,
    Divider, PaginationProps, Pagination,
} from 'antd';
import { LikeOutlined, MessageOutlined, StarOutlined } from '@ant-design/icons';

import KnowledgeListContent from './knowledgeListContent';
import StandardFormRow from '../components/StandardFormRow';
import TagSelect from '@/components/TagSelect';
import type { FormInstance } from 'antd/es/form';

import {KnowledgePublicListRequest} from '../service';

import styles from './index.less';
import {
    getKnowledgeTypesData,
    KnowledgeUserListRequest
} from "@/pages/Dashboard/Knowledge/service";
import {uniqueId} from "lodash";
import {KnowledgeListResponse, KnowledgePublicListRequestParams} from '../data';

const { Search } = Input;
const { Option } = Select;
const FormItem = Form.Item;


const KnowledgeSearch= (
    {
        nodeKeys,
        setNodeKeys,
    }:{
        nodeKeys:string[];
        setNodeKeys:(node:any)=>void;
    }
) => {
    const [ authors,setAuthors ] = useState<any[]>([]);
    const [ loading,setLoading ] = useState(false);
    const [total, setTotal] = useState("0");
    const [ dataList,setDataList ] = useState<any[]>();
    const [ pageSize,setPageSize ] = useState("5");
    const [ currentPage,setCurrentPage ] = useState("1");
    const onChange: PaginationProps['onChange'] = page => {
        setCurrentPage(page.toString());
    };
    const onShowSizeChange: PaginationProps['onShowSizeChange'] = (current, pageSize) => {
        setCurrentPage(current.toString());
        setPageSize(pageSize.toString());
        // console.log(current, pageSize);
    };
    const formRef = useRef<FormInstance>(null);
    //权限列表
    const PublicList: any[] = [
        {
            title: '授权查阅',
            description:
                '本条知识在本平台可以被检索，公开页面上仅显示标题、摘要等非主体信息，如需阅读下载完整版本，需获得知识产权所有人授权方可继续。',
            value: "0",
        },
        {
            title: '公开发布',
            description: '本条知识完全公开，包括匿名用户在内的所有用户可以免费阅读下载。',
            value: "1",
        },
        {
            title: '仅限会员',
            description: '本条知识在本平台内完全公开，仅限本平台用户内登录后免费阅读下载。',
            value: "2",
        },

    ];

    useEffect(()=>{
        const vals:any = formRef.current?.getFieldsValue();
        getKnowledgeList({
            ...vals,
        });
    },[currentPage,pageSize,nodeKeys])

    useEffect(()=>{
        appendData();
    },[])

    const submit=()=>{
        const vals:any = formRef.current?.getFieldsValue();
        getKnowledgeList({
            ...vals,
        });
    }


    // @ts-ignore
    const onValuesChange = async (changedValues:any,allValues:any) => {
        getKnowledgeList({
            ...allValues,
            // classificationCodes
        });
    }

    //获取作者列表
    const appendData = () => {
        KnowledgeUserListRequest({
            userName:""
        }).then((res)=>{
            if(res.code == 200){
                const result:any[] = [];
                if(res.data.length>0){
                    res.data.map((item)=>{
                        result.push( {
                            label:item.name,
                            value:item.id,
                        })
                    })
                    setAuthors(result);
                }
            }
            else{
            }
        });
    };

    const IconText: React.FC<{
        type: string;
        text: React.ReactNode;
    }> = ({ type, text }) => {
        switch (type) {
            case 'star-o':
                return (
                    <span>
                        <StarOutlined style={{ marginRight: 8 }} />
                        {text}
                    </span>
                );
            case 'like-o':
                return (
                    <span>
                        <LikeOutlined style={{ marginRight: 8 }} />
                        {text}
                    </span>
                );
            case 'message':
                return (
                    <span>
                        <MessageOutlined style={{ marginRight: 8 }} />
                        {text}
                    </span>
                );
            default:
                return null;
        }
    };


    //获取目录树结构，使其与组件可识别的结构一致
    const getSedTree = (data?: AircasKB.Knowledge.classificationListResponse[]) => {
        let office = data?.map(item => {
            // @ts-ignore
            const result:any = {
                title:item.name,
                value:item.code,
                key:item.code,
                children:getSedTree(item.childList)
            }
            return result
        })
        return office
    }



    const formItemLayout = {
        wrapperCol: {
            xs: { span: 24 },
            sm: { span: 24 },
            md: { span: 12 },
        },
    };

    const getKnowledgeList = async (
        {
            authorId,
            keyword,
            permissionType,
            types,
        }:{
            authorId?:string;//作者
            keyword?:string;//关键词
            permissionType?:string;//私密类型
            types?:string[];//知识类型
        }
    ) => {
        setLoading(true);
        let classificationCodes:any[]= [];
        if(nodeKeys){
            classificationCodes = nodeKeys;
        }
        const codes:any =  classificationCodes.length>0?classificationCodes:undefined;
        const requestParams:KnowledgePublicListRequestParams = {
            currentPage,
            pageSize,
            authorId,
            classificationCodes:codes,
            keyword,
            permissionType,
            types,
        }
        const res:AircasKB.ResponseType<KnowledgeListResponse> = await KnowledgePublicListRequest(requestParams);
        if(res.code == 200){
            let result: any[] = [];
            res.data.list?.map((item) => {
                let onwer: string = "";
                // @ts-ignore
                for (let i = 0; i < item.authorNames?.length; i++) {
                    // @ts-ignore
                    onwer += item.authorNames[i] + ',';
                }
                // @ts-ignore
                if (item.authorNames?.length > 0) {
                    onwer += '等' + item.authorNames?.length + "人";
                }
                result.push({
                    ...item,
                    onwer,
                    avatar: 'https://joeschmoe.io/api/v1/random'
                })
            })
            setDataList(result);
            // @ts-ignore
            setTotal(res.data.total);
        }
        setLoading(false);
    }





    return (
        <>
            <Card bordered={false}>
                <Form
                    ref={formRef}
                    layout="inline"
                >
                    <StandardFormRow title="所属类目" block style={{ paddingBottom: 11 }}>
                        <FormItem name="types">
                            <KnowledgeTypeSelector />
                        </FormItem>
                    </StandardFormRow>
                    <StandardFormRow title="其它选项" grid>
                        <Space split={<Divider type="vertical" />}>
                            <FormItem {...formItemLayout} label="作者" name="authorId">
                                <Select  placeholder="不限" style={{ maxWidth: 200, width: 150 }}>
                                    <Option key={uniqueId()} value="">不限</Option>
                                    { authors?.length>0 &&authors?.map((item)=>{
                                        return (
                                            <Option key={uniqueId()} value={item.value}>{item.label}</Option>
                                        )
                                    }) }
                                </Select>
                            </FormItem>
                            <FormItem {...formItemLayout} label="好评度" name="rate">
                                <Select placeholder="不限"  style={{ maxWidth: 200, width: 120 }}>
                                    <Option value="">不限</Option>
                                    <Option value="good">优秀</Option>
                                </Select>
                            </FormItem>
                            <FormItem {...formItemLayout} label="公开度" name="permissionType">
                                <Select placeholder="不限"
                                        style={{ maxWidth: 200, width: 120 }}
                                >
                                    <Option key={uniqueId()} value="">不限</Option>
                                    { PublicList?.length>0 &&PublicList?.map((item)=>{
                                        return (
                                            <Option key={uniqueId()} value={item.value}>{item.title}</Option>
                                        )
                                    }) }
                                </Select>
                            </FormItem>
                        </Space>
                    </StandardFormRow>
                    <StandardFormRow title="关键词" grid last>
                        <FormItem name="keyword" {...formItemLayout} >
                            <Search
                                placeholder="请输入关键字"
                                allowClear
                                enterButton="搜索"
                                onSearch={submit}
                                style={{ width: 400 }}
                            />
                        </FormItem>
                    </StandardFormRow>
                </Form>
            </Card>
            <Card bordered={false} className={styles.listWrapper} bodyStyle={{ padding: 0 }}>
                <List
                    size="large"
                    loading={loading}
                    rowKey="id"
                    itemLayout="vertical"
                    dataSource={dataList}
                    renderItem={(item) => (
                        <List.Item
                            // key={item.id}
                            actions={[
                                <IconText key="star" type="star-o" text={item.bookmarkCount} />,
                                <IconText key="like" type="like-o" text={item.likedCount} />,
                                <IconText key="message" type="message" text={item.commentCount} />,
                            ]}
                        >
                            <List.Item.Meta
                                title={
                                    <a
                                        className={styles.listItemMetaTitle}
                                        target="_blank"
                                        href={`/knowledge/details/${item.id}`}
                                    >
                                        {item.title}
                                    </a>
                                }
                                description={
                                    <span>
                                         {
                                             item.classificationNames.map((item:any)=>{
                                                 return(
                                                     <Tag color="blue" key={uniqueId()}>{item.toString()}</Tag>
                                                 )
                                             })
                                         }
                                    </span>
                                }
                            />
                            <KnowledgeListContent data={item} />
                        </List.Item>
                    )}
                />
                <Pagination showSizeChanger onShowSizeChange={onShowSizeChange} showQuickJumper current={Number(currentPage)||1} pageSize={Number(pageSize)||5} total={Number(total)||0} onChange={onChange}
                            showTotal={(total, range)=>{
                                return '显示第 '+range[0] + " 条到第 " + range[1] + " 条记录, 共 " + total + " 条";
                            }}
                            pageSizeOptions={[5,10, 20, 50, 100]}
                />
            </Card>
        </>
    );
};

const KnowledgeTypeSelector = (props: any) => {
    const [ loading,setLoading ] = useState(false);
    const [ items,setItems ] = useState<AircasKB.Knowledge.KnowledgeTypesResponse[]>();
    const getknowledgeTypes  = async () => {
        setLoading(true);
        try{
            const list = await getKnowledgeTypesData();
            setItems(list);
            setLoading(false);
        }
        catch (e) {
            setLoading(false);
        }
    }

    useEffect(()=>{
        getknowledgeTypes()
    },[])

    if (loading) {
        return <div>loading...</div>;
    }
    return (
        <TagSelect {...props} expandable>
            {items?.map((item,index) => {
                return (
                    <TagSelect.Option key={index} value={item.id}>
                        {item.label}
                    </TagSelect.Option>
                );
            })}
        </TagSelect>
    );
};

export default KnowledgeSearch;
